package me.numark.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.text.method.SingleLineTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import me.numark.R;
import me.numark.model.LogInResponse;
import me.numark.net.BaseResponse;
import me.numark.net.NetworkConstants;
import me.numark.net.RequestServerTask;
import me.numark.utils.Constants;
import me.numark.utils.Global;
import me.numark.utils.HttpUtil;
import me.numark.utils.LogUtils;
import me.numark.utils.Settings;
import me.numark.utils.Utils;

/**
 * Created by ytian on 15/7/27.
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.mobile_edit)
    EditText mobileEdit;

    @Bind(R.id.verify_code_edit)
    EditText verifyCodeEdit;

    @Bind(R.id.verify_code_button)
    TextView verifyCodeButton;

    @Bind(R.id.password_icon)
    ImageView passwordIcon;

    @Bind(R.id.password_edit)
    EditText passwordEdit;

    @Bind(R.id.nick_edit)
    EditText nickEdit;

    @Bind(R.id.register_button)
    Button registerButton;

    @Bind(R.id.read_text)
    CheckBox readClauseCheckBox;

    @Bind(R.id.clauses)
    TextView clauses;

    @Bind(R.id.password_layout)
    RelativeLayout passwordLayout;

    @Bind(R.id.clauses_layout)
    LinearLayout clausesLayout;

    @Bind(R.id.divider)
    View divider;

    private boolean verifyOnly;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_register;
        super.onCreate(savedInstanceState);
        verifyOnly = getIntent().getBooleanExtra("verify_only", false);
        initUI();
    }

    private void initUI() {
        if (titleTextView != null) {
            if (verifyOnly) {
                titleTextView.setText(R.string.get_verify_code);
            } else {
                titleTextView.setText(R.string.register);
            }
        }
        registerButton.setOnClickListener(this);
        clauses.setOnClickListener(this);
        verifyCodeButton.setOnClickListener(this);
        passwordIcon.setOnClickListener(this);
        if (verifyOnly) {
            registerButton.setText(getString(android.R.string.ok));
            passwordLayout.setVisibility(View.GONE);
            clausesLayout.setVisibility(View.GONE);
            nickEdit.setVisibility(View.GONE);
            divider.setVisibility(View.GONE);
            registerButton.setText(getString(R.string.next));
            //registerButton.setInputType(InputType.TYPE_NULL);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.register_button:
                if (verifyOnly) {
                    if (!TextUtils.isEmpty(mobileEdit.getText().toString())
                            && !TextUtils.isEmpty(verifyCodeEdit.getText().toString())) {
                        Intent intent = new Intent();
                        intent.putExtra("cellphone",mobileEdit.getText().toString());
                        intent.putExtra("code", verifyCodeEdit.getText().toString());
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                } else if (isInputValid()) {
                    doRegister();
                }
                break;
            case R.id.clauses:
                startActivity(new Intent(RegisterActivity.this,ProtocolActivity.class));
                break;
            case R.id.password_icon:
                passwordIcon.setSelected(!passwordIcon.isSelected());
                passwordEdit.setTransformationMethod(passwordIcon.isSelected() ?
                        SingleLineTransformationMethod.getInstance() :
                        PasswordTransformationMethod.getInstance());
                break;
            case R.id.verify_code_button:
                getVerifyCode();
                break;
        }
    }

    private boolean isInputValid() {
        if (!readClauseCheckBox.isChecked()) {
            return false;
        }
        String mobile = mobileEdit.getText().toString();
        if (mobile.length() != getResources().getInteger(R.integer.mobile_length)) {
            Utils.showToast(R.string.please_input_mobile_number);
            return false;
        }
        String verifyCode = verifyCodeEdit.getText().toString();
        if (verifyCode.length() != getResources().getInteger(R.integer.verify_code_length)) {
            Utils.showToast(R.string.invalid_verify_code);
            return false;
        }
        String password = passwordEdit.getText().toString();
        if (password.length() < getResources().getInteger(R.integer.min_password_length)) {
            Utils.showToast(R.string.password_too_short);
            return false;
        }
        String nick = nickEdit.getText().toString();
        if (nick.length() < getResources().getInteger(R.integer.min_nick_length)) {
            Utils.showToast(R.string.nick_too_short);
            return false;
        }
        return true;
    }

    private static final int MSG_COUNT_DOWN = 30;

    private static final int MSG_COUNT_DOWN_BEGIN = 31;

    private static final int MSG_COUNT_DOWN_FINISHED = 32;

    private int countDown = Constants.SMS_COUNT_DOWN_TIME;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    verifyCodeButton.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    verifyCodeButton.setText(
                            String.format(getString(R.string.count_down_time_left), countDown));
                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        sendEmptyMessage(MSG_COUNT_DOWN_FINISHED);
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    verifyCodeButton.setText(R.string.get_verify_code);
                    verifyCodeButton
                            .setTextColor(getResources().getColor(android.R.color.white));
                    verifyCodeButton.setEnabled(true);
                    countDown = Constants.SMS_COUNT_DOWN_TIME;
                    break;

            }

        }
    };

    private void finishCountdown() {
        countDown = 0;
        mHandler.removeMessages(MSG_COUNT_DOWN);
    }

    @Override
    protected void onDestroy() {
        finishCountdown();
        super.onDestroy();
    }

    private void getVerifyCode() {
        final Map<String, Object> params = new HashMap<>();
        params.put("cellphone", mobileEdit.getText().toString());
        new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(R.string
                .getting_registration_sms)) {
            @Override
            protected String requestServer() {
                return HttpUtil.get(NetworkConstants.REGISTER_URL, params);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                Utils.showToast(R.string.get_registration_sms_success);
            }

        }.setDefaultErrMsg(R.string.get_registration_sms_failed).start();
    }

    private void doRegister() {
        final Map<String, Object> params = new HashMap<>();
        params.put("cellphone", mobileEdit.getText().toString());
        params.put("password", passwordEdit.getText().toString());
        params.put("code", verifyCodeEdit.getText().toString());
        params.put("nick", nickEdit.getText().toString());
        new RequestServerTask<LogInResponse>(LogInResponse.class, this, getString(R.string
                .registering)) {
            @Override
            protected String requestServer() {
                LogUtils.d("post params: " + params);
                return HttpUtil.post(NetworkConstants.REGISTER_URL, params);
            }

            @Override
            protected void onSuccess(LogInResponse result) {
                Utils.showToast(R.string.register_success);
                Settings.saveUser(result.data);
                Global.currentUser = result.data;
                Settings.setCurrentUid(result.data.uid);
                Intent intent = new Intent(RegisterActivity.this, ChooseInterestsActivity.class);
                intent.putExtra("user", Global.getGson().toJson(result.data));
                startActivityForResult(intent, 0);
            }

        }.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }
}
